import hashlib

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .models import User
# Create your views here.


def reg_view(request):
    # 注册
    # GET 返回页面
    # post 处理数据
    # 1.两个密码保持一直
    # 2.当前用户名是否可用
    # 3.插入数据[明文处理密码]
    if request.method == "GET":
        return render(request,'user/register.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password_1 = request.POST['password_1']
        password_2 = request.POST['password_2']
        if password_1 != password_2:
            return HttpResponse('两次密码不一致')
        # 哈希算法 - 给定明文，计算出一段定长的，不可逆的值；md5，sha-256
        # 特点
        # 1.定长输出：不管明文输入的长度为多少，哈希值都是固定的，md5 - 32位16进制
        # 2.不可逆，无法反向计算出对应明文
        # 3.雪崩效应：输入改变，输出必然改变
        # 场景，1.密码处理 2.文件完整性校验
        # 如何使用
        m = hashlib.md5()  # 创建md5对象
        m.update(password_1.encode())
        password_m = m.hexdigest()

        # 2.当前用户名是否可用
        old_users = User.objects.filter(username=username)
        if old_users:
            return HttpResponse('用户名已经存在')
        try:
            user = User.objects.create(username=username,password=password_m)
        except Exception as e:
            # 并发多的时候可能会报错，重复插入，唯一索引，并发写入问题
            print('--create user error %s'%(e))
            return HttpResponse('用户名已经注册')

        # 用户名注册一天 免登录
        request.session['username'] = username
        request.session['uid'] = user.id
        #TODO 修改session存储时间为1天


        # return  HttpResponse("注册成功")
        return HttpResponseRedirect('/index/')  # 跳转到首页

def login_view(request):
    if request.method == "GET":
        # 检查session 是否存在
        if request.session.get('username') and request.session.get('uid'):
            return HttpResponse('已登录')
        # 检查 cookie 是否存在
        c_username = request.COOKIES.get('username')
        c_uid = request.COOKIES.get('uid')
        if c_uid and c_username:
            request.session["username"] = c_username
            request.session["uid"] = c_uid
            # return HttpResponse('已登录')
            return HttpResponseRedirect('/index/')  # 跳转到首页
        return render(request,'user/login.html')
    elif request.method == "POST":
        # 处理数据
        username = request.POST['username']
        password = request.POST['password']

        try:
            user = User.objects.get(username=username)
        except Exception as e:
            print('--login user error %s'%(e))
            return HttpResponse("用户名或者密码错误")

        # 比对密码
        m = hashlib.md5()
        m.update(password.encode())

        if m.hexdigest() != user.password:
            return HttpResponse('用户名或者密码错误')

        # 记录会话状态
        request.session['username'] = username
        request.session['uid'] = user.id  # 主键，查询会比较快
##
        # resp = HttpResponse('--登录成功--')
        resp =  HttpResponseRedirect('/index/')  # 跳转到首页
        # 判断用户是否点选了  记住用户名
        if 'remember' in request.POST:
            resp.set_cookie('username',username,3600*24*3)
            resp.set_cookie('uid',user.id,3600*24*3)

        return resp
        # 点选了 -》 COOKIE 存储 username,uid  时间3天


        # return HttpResponse("---登录成功----")


def logout_view(request):

    # 删除session
    if 'username' in request.session:
        del request.session['username']
    if 'uid' in request.session:
        del request.session['uid']
    resp = HttpResponseRedirect('/index')
    #删除 cookies
    if 'username' in request.COOKIES:
        resp.delete_cookie('username')
    if 'uid' in request.COOKIES:
        resp.delete_cookie('uid')
    return resp